{% extends 'base.html' %}

{% block title %}耗材管理 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    /* 表头样式优化 */
    .table-dark th {
        position: sticky;
        top: 0;
        z-index: 10;
        font-weight: 600;
        vertical-align: middle;
        padding: 12px 8px;
    }

    .table-dark .form-check-input {
        background-color: rgba(255, 255, 255, 0.2) !important;
        border-color: rgba(255, 255, 255, 0.3) !important;
    }

    .table-dark .form-check-input:checked {
        background-color: #fff !important;
        border-color: #fff !important;
    }

    .consumable-table-container {
        max-height: 70vh;
        overflow-y: auto;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .table-responsive {
        border-radius: 8px;
        /* 允许下拉菜单不被裁剪 */
        overflow: visible;
    }

    /* 优化操作列下拉框宽度 */
    .action-dropdown {
        min-width: 160px !important;
    }

    .action-dropdown .dropdown-menu {
        min-width: 200px !important;
        max-width: none !important;
        /* 长列表可滚动，避免超出视口 */
        max-height: 60vh;
        overflow-y: auto;
        /* 文本换行，避免超长内容撑破 */
        white-space: normal;
        word-break: break-word;
        /* 菜单内滚动不影响外层 */
        overscroll-behavior: contain;
    }

    /* 操作按钮组优化 */
    .btn-group-sm .btn {
        padding: 0.25rem 0.4rem;
        font-size: 0.75rem;
    }

    .btn-group-sm .dropdown-toggle::after {
        margin-left: 0.2rem;
    }

    /* 提升小号下拉按钮的点击热区一致性 */
    .btn-group-sm .dropdown-toggle {
        min-width: 32px;
        height: 32px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    /* 去除需要的下拉按钮箭头，避免与图标重复 */
    .no-caret::after {
        display: none !important;
    }

    /* 改善可访问性的聚焦可视化 */
    .btn:focus-visible {
        outline: 2px solid rgba(13, 110, 253, 0.6);
        outline-offset: 2px;
    }

    /* 库存状态样式 */
    .stock-status {
        min-width: 80px;
    }

    .stock-badge {
        font-size: 0.8rem;
        padding: 0.25rem 0.5rem;
    }

    /* 快速操作按钮样式 */
    .quick-action-btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
        border-radius: 0.25rem;
        min-width: 32px;
        height: 32px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .stock-in-btn {
        background: linear-gradient(135deg, #28a745, #20c997);
        border: none;
        color: white;
        box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
    }

    .stock-in-btn:hover {
        background: linear-gradient(135deg, #218838, #1ea085);
        color: white;
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(40, 167, 69, 0.4);
    }

    .stock-out-btn {
        background: linear-gradient(135deg, #fd7e14, #ffc107);
        border: none;
        color: white;
        box-shadow: 0 2px 4px rgba(253, 126, 20, 0.3);
    }

    .stock-out-btn:hover {
        background: linear-gradient(135deg, #e8690b, #e0a800);
        color: white;
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(253, 126, 20, 0.4);
    }

    /* 操作列布局优化 */
    .operation-buttons {
        display: flex;
        align-items: center;
        gap: 4px;
        flex-wrap: nowrap;
        min-width: 160px;
    }

    .operation-buttons .btn-group {
        flex-shrink: 0;
    }

    /* 表格列宽优化 */
    .consumable-table th:nth-child(1) {
        width: 3%;
    }

    /* 复选框 */
    .consumable-table th:nth-child(2) {
        width: 18%;
    }

    /* 耗材名称 */
    .consumable-table th:nth-child(3) {
        width: 8%;
    }

    /* 编码 */
    .consumable-table th:nth-child(4) {
        width: 8%;
    }

    /* 类别 */
    .consumable-table th:nth-child(5) {
        width: 8%;
    }

    /* 仓库 */
    .consumable-table th:nth-child(6) {
        width: 5%;
    }

    /* 单位 */
    .consumable-table th:nth-child(7) {
        width: 10%;
    }

    /* 库存状态 */
    .consumable-table th:nth-child(8) {
        width: 6%;
    }

    /* 最低库存 */
    .consumable-table th:nth-child(9) {
        width: 8%;
    }

    /* 采购单价 */
    .consumable-table th:nth-child(10) {
        width: 8%;
    }

    /* 供应商 */
    .consumable-table th:nth-child(11) {
        width: 18%;
    }

    /* 操作 */

    /* 库存状态优化 */
    .stock-status {
        min-width: 70px;
        text-align: center;
    }

    .stock-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        font-weight: 600;
    }

    /* 提升下拉层级以覆盖表头/其它元素 */
    .dropdown-menu {
        z-index: 2000;
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb bg-white py-2 px-3 rounded shadow-sm mb-3">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}"><i class="fas fa-home me-1"></i>首页</a></li>
                <li class="breadcrumb-item active" aria-current="page"><i class="fas fa-boxes me-1"></i>耗材管理</li>
            </ol>
        </nav>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="fas fa-boxes me-2"></i>耗材管理</h2>
            <div class="btn-group">
                <a href="#" class="btn btn-primary" id="btnOpenCreateModal" data-modal-url="{% url 'assets:consumable_create' %}" data-modal-title="新增耗材">
                    <i class="fas fa-plus me-1"></i>新增耗材
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split no-caret"
                    data-bs-toggle="dropdown" data-bs-boundary="viewport" data-bs-offset="0,8" data-bs-auto-close="outside" data-bs-placement="bottom-end"
                    data-bs-toggle-second="tooltip" data-bs-title="更多操作"
                    aria-haspopup="true" aria-expanded="false" aria-label="更多操作">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'assets:inventory_log_list' %}">
                            <i class="fas fa-history me-2"></i>库存记录
                        </a></li>
                    <li><a class="dropdown-item" href="{% url 'assets:inventory_alert_list' %}">
                            <i class="fas fa-exclamation-triangle me-2"></i>库存预警
                        </a></li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li>
                        <a class="dropdown-item" href="{% url 'assets:consumable_low_stock' %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}">
                            <i class="fas fa-level-down-alt me-2"></i>仅看低库存
                        </a>
                    </li>
                    <li>
                        <a class="dropdown-item" href="{% url 'assets:consumable_export' %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}">
                            <i class="fas fa-file-export me-2"></i>导出(按当前筛选)
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <!-- 搜索和过滤区域 -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-search me-2"></i>搜索与筛选</h5>
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#filterCollapse">
                        <i class="fas fa-filter me-1"></i>筛选
                    </button>
                </div>
            </div>
            <div class="collapse show" id="filterCollapse">
                <div class="card-body pt-3">
                    <form method="get" class="row g-3">
                        <div class="col-md-3">
                            <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="搜索耗材名称或编码..."
                                value="{{ search_query }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search me-1"></i>搜索
                            </button>
                        </div>
                    </div>
                    <div style="min-width: 120px;">
                        <select class="form-select form-select-sm" name="status" onchange="this.form.submit()">
                            <option value="">全部状态</option>
                            <option value="low_stock" {% if request.GET.status == "low_stock" %}selected{% endif %}>库存不足
                            </option>
                            <option value="normal" {% if request.GET.status == "normal" %}selected{% endif %}>库存正常
                            </option>
                            <option value="out_of_stock" {% if request.GET.status == "out_of_stock" %}selected{% endif %}>
                                缺货</option>
                        </select>
                    </div>
                    <div style="min-width: 120px;">
                        <select class="form-select form-select-sm" name="warehouse" onchange="this.form.submit()">
                            <option value="">全部仓库</option>
                            {% for warehouse in warehouses %}
                            <option value="{{ warehouse.id }}" {% if request.GET.warehouse == warehouse.id|stringformat:"s" %}selected{% endif %}>{{ warehouse.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div style="min-width: 120px;">
                        <select class="form-select form-select-sm" name="category" onchange="this.form.submit()">
                            <option value="">全部类别</option>
                            {% for category in categories %}
                            <option value="{{ category.id }}" {% if request.GET.category == category.id|stringformat:"s" %}selected{% endif %}>{{ category.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div style="min-width: 120px;">
                        <select class="form-select form-select-sm" name="supplier" onchange="this.form.submit()">
                            <option value="">全部供应商</option>
                            {% for supplier in suppliers %}
                            <option value="{{ supplier.id }}" {% if request.GET.supplier == supplier.id|stringformat:"s" %}selected{% endif %}>{{ supplier.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="clearSearch()">
                            <i class="fas fa-times me-1"></i>清除
                        </button>
                    </div>

            <!-- 搜索和筛选 -->
            <!-- 搜索和过滤区域 -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-search me-2"></i>搜索与筛选</h5>
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#filterCollapse">
                            <i class="fas fa-filter me-1"></i>筛选
                        </button>
                    </div>
                </div>
                <div class="collapse show" id="filterCollapse">
                    <div class="card-body pt-3">
                        <form method="get" class="row g-3">
                            <div class="col-md-3">
                                <div class="input-group">
                                <input type="text" class="form-control" name="search" placeholder="搜索耗材名称或编码..."
                                    value="{{ search_query }}">
                                <button class="btn btn-outline-secondary" type="submit">
                                    <i class="fas fa-search me-1"></i>搜索
                                </button>
                            </div>
                        </div>
                        <div style="min-width: 120px;">
                            <select class="form-select form-select-sm" name="status" onchange="this.form.submit()">
                                <option value="">全部状态</option>
                                <option value="low_stock" {% if request.GET.status == "low_stock" %}selected{% endif %}>库存不足
                                </option>
                                <option value="normal" {% if request.GET.status == "normal" %}selected{% endif %}>库存正常
                                </option>
                                <option value="out_of_stock" {% if request.GET.status == "out_of_stock" %}selected{% endif %}>
                                    缺货</option>
                            </select>
                        </div>
                        <div style="min-width: 120px;">
                            <select class="form-select form-select-sm" name="warehouse" onchange="this.form.submit()">
                                <option value="">全部仓库</option>
                                {% for warehouse in warehouses %}
                                <option value="{{ warehouse.id }}" {% if request.GET.warehouse == warehouse.id|stringformat:"s" %}selected{% endif %}>{{ warehouse.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div style="min-width: 120px;">
                            <select class="form-select form-select-sm" name="category" onchange="this.form.submit()">
                                <option value="">全部类别</option>
                                {% for category in categories %}
                                <option value="{{ category.id }}" {% if request.GET.category == category.id|stringformat:"s" %}selected{% endif %}>{{ category.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div style="min-width: 120px;">
                            <select class="form-select form-select-sm" name="supplier" onchange="this.form.submit()">
                                <option value="">全部供应商</option>
                                {% for supplier in suppliers %}
                                <option value="{{ supplier.id }}" {% if request.GET.supplier == supplier.id|stringformat:"s" %}selected{% endif %}>{{ supplier.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div>
                            <button type="button" class="btn btn-outline-info btn-sm" onclick="clearSearch()">
                                <i class="fas fa-times me-1"></i>清除
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 耗材列表 -->
            <!-- 耗材列表 -->
            <div class="card border-0 shadow-sm consumable-density-comfortable" id="consumableListRoot">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="mb-0">
                            <i class="fas fa-boxes me-2"></i>耗材列表
                            {% if page_obj %}
                            <span class="badge bg-primary ms-2">{{ page_obj.paginator.count }}</span>
                            {% endif %}
                        </h5>
                    </div>
                    <div class="d-flex align-items-center">
                        <!-- 密度切换 -->
                        <div class="btn-group btn-group-sm density-toggle me-3" role="group">
                            <button type="button" class="btn btn-outline-secondary active" data-density="comfortable">
                                <i class="fas fa-compress-alt"></i> 舒适
                            </button>
                            <button type="button" class="btn btn-outline-secondary" data-density="compact">
                                <i class="fas fa-compress-arrows-alt"></i> 紧凑
                            </button>
                        </div>
                        
                        <!-- 新增按钮 -->
                        <a href="{% url 'assets:consumable_create' %}" 
                           class="btn btn-primary btn-sm"
                           data-bs-toggle="modal" 
                           data-bs-target="#consumableFormModal"
                           data-modal-url="{% url 'assets:consumable_create' %}">
                            <i class="fas fa-plus me-1"></i> 新增耗材
                        </a>
                    </div>
                </div>
                
                <!-- 选择工具条 -->
                <div id="selectionToolbar" class="selection-toolbar">
                    <div>
                        <i class="fas fa-check-square me-1"></i>
                        <span id="selectedCount">0</span> 项已选择
                    </div>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="btnClearSelection">
                            <i class="fas fa-times me-1"></i> 取消选择
                        </button>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="batchActionsDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-tasks me-1"></i> 批量操作
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="batchActionsDropdown">
                                <li><a class="dropdown-item" href="#" id="btnBatchExport"><i class="fas fa-file-export me-1"></i>导出选中</a></li>
                                <li><a class="dropdown-item text-danger" href="#" id="btnBatchDelete"><i class="fas fa-trash-alt me-1"></i>删除选中</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 consumable-table">
                            <thead class="table-light">
                                <tr>
                                    <th width="4%">
                                        <input type="checkbox" class="form-check-input" id="selectAllHeader" onchange="toggleSelectAll()" title="全选/取消全选">
                                    </th>
                                    <th>耗材名称</th>
                                    <th>编码</th>
                                    <th>类别</th>
                                    <th>仓库</th>
                                    <th>库存数量</th>
                                    <th>单位</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for consumable in page_obj %}
                                <tr data-id="{{ consumable.pk }}">
                                    <td>
                                        <input type="checkbox" class="form-check-input asset-checkbox" value="{{ consumable.pk }}" onchange="updateSelection()">
                                    </td>
                                    <td>
                                        <a href="{% url 'assets:consumable_detail' consumable.pk %}" class="text-primary fw-bold">
                                            {{ consumable.name }}
                                        </a>
                                    </td>
                                    <td>{{ consumable.code|default:"-" }}</td>
                                    <td>{{ consumable.category.name|default:"-" }}</td>
                                    <td>{{ consumable.warehouse.name|default:"-" }}</td>
                                    <td class="text-end">
                                        <span class="badge {% if consumable.quantity <= consumable.min_quantity|default:0|add:0 %}bg-danger{% else %}bg-success{% endif %}">
                                            {{ consumable.quantity|default:0 }}{% if consumable.unit %}{{ consumable.unit }}{% endif %}
                                        </span>
                                    </td>
                                    <td>{{ consumable.unit|default:"-" }}</td>
                                    <td>
                                        <span class="badge {% if consumable.status == 'in_stock' %}bg-success{% else %}bg-secondary{% endif %}">
                                            {{ consumable.get_status_display }}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="operation-buttons">
                                            {% with name_escaped=consumable.name|escapejs unit_escaped=consumable.unit|escapejs %}
                                            <button class="btn btn-sm btn-outline-primary" 
                                                    data-pk="{{ consumable.pk }}"
                                                    data-name="{{ name_escaped }}"
                                                    data-unit="{{ unit_escaped }}"
                                                    onclick="handleQuickStockIn(this);"
                                                    title="快速入库">
                                                <i class="fas fa-arrow-down"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-warning" 
                                                    data-pk="{{ consumable.pk }}"
                                                    data-name="{{ name_escaped }}"
                                                    data-unit="{{ unit_escaped }}"
                                                    data-quantity="{{ consumable.quantity|default:0 }}"
                                                    onclick="handleQuickStockOut(this);"
                                                    title="快速出库"
                                                    {% if not consumable.quantity %}disabled{% endif %}>
                                                <i class="fas fa-arrow-up"></i>
                                            </button>
                                            {% endwith %}
                                            <div class="dropdown d-inline-block">
                                                    <i class="fas fa-ellipsis-v"></i>
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="moreActions-{{ consumable.pk }}">
                                                    <li><a class="dropdown-item" href="{% url 'assets:consumable_detail' consumable.pk %}">
                                                        <i class="fas fa-eye me-2 text-info"></i>查看详情
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" data-action="edit" data-id="{{ consumable.pk }}">
                                                        <i class="fas fa-edit me-2 text-primary"></i>编辑
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" data-action="delete" data-id="{{ consumable.pk }}" data-name="{{ consumable.name|escapejs }}">
                                                        <i class="fas fa-trash-alt me-2 text-danger"></i>删除
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    {% if consumable.category %}
                                    <span class="badge bg-secondary">{{ consumable.category.name }}</span>
                                    {% else %}
                                    <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if consumable.warehouse %}
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-warehouse me-1 text-success"></i>
                                        <span title="{{ consumable.warehouse.name }}">{{ consumable.warehouse.name|truncatechars:8 }}</span>
                                    </div>
                                    {% else %}
                                    <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark">{{ consumable.unit }}</span>
                                </td>
                                <td>
                                    <div class="stock-status">
                                        {% if consumable.quantity <= 0 %}
                                            <span class="badge bg-dark stock-badge">{{ consumable.quantity }}</span>
                                            <small class="text-dark d-block">缺货</small>
                                        {% elif consumable.quantity <= consumable.min_quantity %}
                                            <span class="badge bg-danger stock-badge">{{ consumable.quantity }}</span>
                                            <small class="text-danger d-block">库存不足</small>
                                        {% elif consumable.quantity <= consumable.min_quantity|add:10 %}
                                            <span class="badge bg-warning stock-badge">{{ consumable.quantity }}</span>
                                            <small class="text-warning d-block">库存偏低</small>
                                        {% else %}
                                            <span class="badge bg-success stock-badge">{{ consumable.quantity }}</span>
                                            <small class="text-success d-block">库存正常</small>
                                        {% endif %}
                                    </div>
                                </td>
                                <td>
                                    <span class="text-info fw-bold">{{ consumable.min_quantity }}</span>
                                </td>
                                    {% if consumable.purchase_price %}
                                    <span class="text-success fw-bold">¥{{ consumable.purchase_price|floatformat:2 }}</span>
                                    {% else %}
                                    <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if consumable.supplier %}
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-truck me-1 text-info"></i>
                                        <span title="{{ consumable.supplier.name }}">{{ consumable.supplier.name|truncatechars:8 }}</span>
                                    </div>
                                    {% else %}
                                    <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                                        {% if consumable.quantity %}
                                        <button type="button" class="btn btn-sm btn-outline-warning"
                                            onclick="quickStockOut('{{ consumable.pk|escapejs }}', '{{ consumable.name|escapejs }}', '{{ consumable.unit|escapejs }}', '{{ consumable.quantity|default:0|escapejs }}')"
                                            title="快速出库">
                                            <i class="fas fa-arrow-up"></i>
                                        </button>
                                        {% else %}
                                        <button type="button" class="btn quick-action-btn" disabled
                                            style="background: #e9ecef; border: 1px solid #dee2e6;" title="库存不足，无法出库">
                                            <i class="fas fa-minus text-muted"></i>
{{ ... }}
                                        </button>
                                        {% endif %}

                                        <!-- 主要操作按钮 -->
                                        <div class="btn-group btn-group-sm">
                                            <a href="{% url 'assets:consumable_detail' consumable.pk %}"
                                                class="btn btn-outline-info" title="查看详情">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="#" class="btn btn-outline-primary" title="编辑"
                                                data-open-modal data-modal-url="{% url 'assets:consumable_update' consumable.pk %}" data-modal-title="编辑耗材 - {{ consumable.name|escapejs }}">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <div class="btn-group btn-group-sm action-dropdown position-static">
                                                <button id="moreActions-{{ consumable.pk }}" type="button" class="btn btn-outline-secondary dropdown-toggle no-caret"
                                                    data-bs-toggle="dropdown" data-bs-boundary="viewport" data-bs-offset="0,8" data-bs-auto-close="outside" data-bs-placement="bottom-end"
                                                    data-bs-toggle-second="tooltip" data-bs-title="更多操作"
                                                    title="更多操作" aria-haspopup="true" aria-expanded="false" aria-label="更多操作"
                                                    aria-controls="moreActionsMenu-{{ consumable.pk }}">
                                                    <i class="fas fa-ellipsis-v"></i>
                                                </button>
                                                <ul id="moreActionsMenu-{{ consumable.pk }}" class="dropdown-menu dropdown-menu-end" role="menu" aria-labelledby="moreActions-{{ consumable.pk }}">
                                                    <li><a class="dropdown-item"
                                                            href="{% url 'assets:inventory_log_list' %}?search={{ consumable.name }}">
                                                            <i class="fas fa-history me-2 text-primary"></i>库存记录
                                                        </a></li>
                                                    <li><a class="dropdown-item" href="#"
                                                            data-action="printLabel" data-id="{{ consumable.pk }}" data-name="{{ consumable.name|escapejs }}">
                                                            <i class="fas fa-print me-2 text-secondary"></i>打印标签
                                                        </a></li>
                                                    <li><a class="dropdown-item" href="#"
                                                            data-action="exportConsumable" data-id="{{ consumable.pk }}" data-name="{{ consumable.name|escapejs }}">
                                                            <i class="fas fa-download me-2 text-success"></i>导出数据
                                                        </a></li>
                                                    <li>
                                                        <hr class="dropdown-divider">
                                                    </li>
                                                    <li><a class="dropdown-item" href="#"
                                                            data-action="duplicateConsumable" data-id="{{ consumable.pk }}" data-name="{{ consumable.name|escapejs }}">
                                                            <i class="fas fa-copy me-2 text-info"></i>复制耗材
                                                        </a></li>
                                                    <li>
                                                        <hr class="dropdown-divider">
                                                    </li>
                                                    <li><a class="dropdown-item text-danger"
                                                            href="#"
                                                            data-modal="confirm"
                                                            data-post-url="{% url 'assets:consumable_delete' consumable.pk %}"
                                                            data-title="删除耗材"
                                                            data-message="确定要删除耗材『{{ consumable.name|escapejs }}』吗？此操作不可撤销！">
                                                            <i class="fas fa-trash me-2"></i>删除
                                                        </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="10" class="text-center py-4">
                                    <div class="text-muted">
                                        <i class="fas fa-boxes fa-2x mb-2"></i>
                                        <p class="mb-0">暂无耗材数据</p>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 分页 -->
        {% if page_obj.has_other_pages %}
        <nav aria-label="页面导航" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link"
                        href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.warehouse %}&warehouse={{ request.GET.warehouse }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.supplier %}&supplier={{ request.GET.supplier }}{% endif %}{% if request.GET.low_stock %}&low_stock={{ request.GET.low_stock }}{% endif %}">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                </li>
                {% endif %}

                {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                <li class="page-item active">
                    <span class="page-link">{{ num }}</span>
                </li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item">
                    <a class="page-link"
                        href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.warehouse %}&warehouse={{ request.GET.warehouse }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.supplier %}&supplier={{ request.GET.supplier }}{% endif %}{% if request.GET.low_stock %}&low_stock={{ request.GET.low_stock }}{% endif %}">{{
                        num }}</a>
                    </li>
                    {% endif %}
                    {% endfor %}

                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link"
                            href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.warehouse %}&warehouse={{ request.GET.warehouse }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.supplier %}&supplier={{ request.GET.supplier }}{% endif %}{% if request.GET.low_stock %}&low_stock={{ request.GET.low_stock }}{% endif %}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<!-- Toast 提示 -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="toast" class="toast align-items-center text-white bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="d-flex">
            <div id="toastBody" class="toast-body"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    </div>
</div>

<!-- 快速入库模态框 -->
<div class="modal fade" id="quickStockInModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-arrow-down me-2 text-success"></i>快速入库
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="quickStockInForm" method="post">
                {% csrf_token %}
                <input type="hidden" name="action" value="quick_stock_in">
                <input type="hidden" name="consumable_id" id="stockInConsumableId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">耗材名称</label>
                        <input type="text" class="form-control" id="stockInConsumableName" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">入库数量</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="quantity" id="stockInQuantity" step="0.01"
                                min="0.01" required>
                            <span class="input-group-text" id="stockInUnit"></span>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">入库说明</label>
                        <textarea class="form-control" name="description" rows="3"
                            placeholder="请输入入库原因或说明..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check me-1"></i>确认入库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 快速出库模态框 -->
<div class="modal fade" id="quickStockOutModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-arrow-up me-2 text-warning"></i>快速出库
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="quickStockOutForm" method="post">
                {% csrf_token %}
                <input type="hidden" name="action" value="quick_stock_out">
                <input type="hidden" name="consumable_id" id="stockOutConsumableId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">耗材名称</label>
                        <input type="text" class="form-control" id="stockOutConsumableName" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">出库数量</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="quantity" id="stockOutQuantity" step="0.01"
                                min="0.01" required>
                            <span class="input-group-text" id="stockOutUnit"></span>
                        </div>
                        <div class="form-text">当前库存: <span id="currentStock"></span></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">出库说明</label>
                        <textarea class="form-control" name="description" rows="3"
                            placeholder="请输入出库原因或说明..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-check me-1"></i>确认出库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>



<!-- 确认操作模态框（POST 提交） -->
<div class="modal fade" id="confirmActionModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="confirmActionTitle">确认操作</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
      </div>
      <div class="modal-body">
        <pre id="confirmActionMessage" class="mb-0" style="white-space:pre-wrap;"></pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="confirmActionBtn" data-post-url="">确定</button>
      </div>
    </div>
  </div>
  </div>

<!-- 全局成功 Toast 容器（居中置顶） -->
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 1080;">
  <div id="globalToast" class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="d-flex">
      <div class="toast-body" id="globalToastBody">操作成功</div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
    // 快速入库
   function quickStockIn(consumableId, consumableName, unit) {
       // Ensure consumableId is a number
       const consumableIdNum = parseInt(consumableId, 10);
       if (isNaN(consumableIdNum)) {
           console.error('Invalid consumable ID:', consumableId);
           return;
       }

       // Create a new modal instance if it doesn't exist
       let modal = document.getElementById('quickStockInModal');
       if (!modal) {
           modal = document.createElement('div');
           modal.className = 'modal fade';
           modal.id = 'quickStockInModal';
           modal.innerHTML = `
               <div class="modal-dialog">
                   <div class="modal-content">
                       <div class="modal-header">
                           <h5 class="modal-title">快速入库 - ${consumableName || ''}</h5>
                           <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                       </div>
                       <form id="quickStockInForm" method="post" action="{% url 'assets:consumable_quick_stock_in' %}">
                           {% csrf_token %}
                           <div class="modal-body">
                               <input type="hidden" name="consumable_id" id="id_consumable_id" value="">
                               <div class="mb-3">
                                   <label for="id_quantity" class="form-label">入库数量</label>
                                   <div class="input-group">
                                       <input type="number" class="form-control" id="id_quantity" name="quantity" min="1" value="1" required>
                                       <span class="input-group-text unit-display">${unit || ''}</span>
                                   </div>
                               </div>
                               <div class="mb-3">
                                   <label for="id_notes" class="form-label">备注</label>
                                   <textarea class="form-control" id="id_notes" name="notes" rows="2"></textarea>
                               </div>
                           </div>
                           <div class="modal-footer">
                               <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                               <button type="submit" class="btn btn-primary">确认入库</button>
                           </div>
                       </form>
                   </div>
               </div>
           `;
           document.body.appendChild(modal);
       }
       
       // Initialize the modal if it's not already initialized
       const modalInstance = new bootstrap.Modal(modal);
       
       // Update modal content
       modal.querySelector('.modal-title').textContent = `快速入库 - ${consumableName || ''}`;
       modal.querySelector('.unit-display').textContent = unit || '';
       modal.querySelector('#id_consumable_id').value = consumableIdNum;
       
       // Reset form
       const form = modal.querySelector('form');
       form.reset();
       form.querySelector('#id_quantity').value = '1';
       
       // Show the modal
       modalInstance.show();
       
       // Focus on quantity input after a short delay to ensure the modal is fully visible
       setTimeout(() => {
           const quantityInput = modal.querySelector('#id_quantity');
           if (quantityInput) quantityInput.focus();
       }, 500);
   }

    // 快速出库
    function quickStockOut(consumableId, consumableName, unit, currentQuantity) {
        // Ensure consumableId is a number
        const consumableIdNum = parseInt(consumableId, 10);
        if (isNaN(consumableIdNum)) {
            console.error('Invalid consumable ID:', consumableId);
            return;
        }
        
        // Convert currentQuantity to a number
        const currentQty = parseInt(currentQuantity, 10) || 0;
        
        // Create a new modal instance if it doesn't exist
        let modal = document.getElementById('quickStockOutModal');
        if (!modal) {
            modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.id = 'quickStockOutModal';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">快速出库 - ${consumableName || ''}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <form id="quickStockOutForm" method="post" action="{% url 'assets:consumable_quick_stock_out' %}">
                            {% csrf_token %}
                            <div class="modal-body">
                                <input type="hidden" name="consumable_id" id="id_consumable_id" value="">
                                <div class="mb-3">
                                    <label class="form-label">当前库存</label>
                                    <div class="alert alert-info py-2 mb-3">
                                        <i class="fas fa-boxes me-2"></i>
                                        <span class="current-stock fw-bold">0</span>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="id_quantity" class="form-label">出库数量</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="id_quantity" name="quantity" min="1" value="1" required>
                                        <span class="input-group-text unit-display">${unit || ''}</span>
                                    </div>
                                    <small class="text-muted d-block mt-1">最大可出库: <span class="max-quantity">0</span> ${unit || ''}</small>
                                </div>
                                <div class="mb-3">
                                    <label for="id_notes" class="form-label">出库原因/备注</label>
                                    <textarea class="form-control" id="id_notes" name="notes" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-warning">确认出库</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
        
        // Initialize the modal if it's not already initialized
        const modalInstance = new bootstrap.Modal(modal);
        
        // Update modal content
        modal.querySelector('.modal-title').textContent = `快速出库 - ${consumableName || ''}`;
        modal.querySelector('.current-stock').textContent = `${currentQty} ${unit || ''}`;
        modal.querySelector('#id_consumable_id').value = consumableIdNum;
        
        // Set max quantity and update display
        const quantityInput = modal.querySelector('#id_quantity');
        quantityInput.value = '1';
        quantityInput.max = currentQty;
        modal.querySelector('.max-quantity').textContent = currentQty;
        
        // Reset notes
        modal.querySelector('#id_notes').value = '';
        
        // Update unit display
        const unitDisplays = modal.querySelectorAll('.unit-display');
        unitDisplays.forEach(display => {
            display.textContent = unit || '';
        });
        
        // Show the modal
        modalInstance.show();
        
        // Focus on quantity input after a short delay to ensure the modal is fully visible
        setTimeout(() => {
            if (quantityInput) quantityInput.focus();
        }, 500);
        
        // Add form validation
        const form = modal.querySelector('form');
        form.onsubmit = function(e) {
            const quantity = parseInt(quantityInput.value, 10) || 0;
            if (isNaN(quantity) || quantity <= 0) {
                e.preventDefault();
                alert('请输入有效的出库数量');
                return false;
            }
            if (quantity > currentQty) {
                e.preventDefault();
                alert(`出库数量不能超过当前库存 (${currentQty}${unit ? ' ' + unit : ''})`);
                return false;
            }
            return true;
        };
    }

    function printLabel(consumableId, consumableName) {
        alert(`打印标签功能开发中...\n耗材: ${consumableName} (ID: ${consumableId})`);
    }

    function exportConsumable(consumableId, consumableName) {
        alert(`导出数据功能开发中...\n耗材: ${consumableName} (ID: ${consumableId})`);
    }

    function duplicateConsumable(consumableId, consumableName) {
        if (confirm(`确定要复制耗材 "${consumableName}" 吗？`)) {
            alert(`复制耗材功能开发中...\n耗材: ${consumableName} (ID: ${consumableId})`);
        }
    }

    function clearSearch() {
        window.location.href = '{% url "assets:consumable_list" %}';
    }

    // 统一委托点击事件，替代内联 onclick
    document.addEventListener('click', function (e) {
        const el = e.target.closest('[data-action]');
        if (!el) return;

        const action = el.getAttribute('data-action');
        const id = el.getAttribute('data-id');
        const name = el.getAttribute('data-name');
        const unit = el.getAttribute('data-unit');
        const qty = el.getAttribute('data-qty');

        switch (action) {
            case 'quickStockIn':
                quickStockIn(id, name, unit);
                break;
            case 'quickStockOut':
                quickStockOut(id, name, unit, qty);
                break;
            case 'printLabel':
                e.preventDefault();
                printLabel(id, name);
                break;
            case 'exportConsumable':
                e.preventDefault();
                exportConsumable(id, name);
                break;
            case 'duplicateConsumable':
                e.preventDefault();
                duplicateConsumable(id, name);
                break;
        }
    });

    // 初始化下拉按钮上的提示（避免与 dropdown 的 data-bs-toggle 冲突）
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.dropdown-toggle[data-bs-title]').forEach(function (el) {
            new bootstrap.Tooltip(el, {
                title: el.getAttribute('data-bs-title'),
                trigger: 'hover focus',
                placement: 'bottom'
            });
        });
    });

    // 处理快速入库表单提交
    document.getElementById('quickStockInForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const consumableId = formData.get('consumable_id');
        const quantity = formData.get('quantity');
        const description = formData.get('description');

        // 这里可以添加AJAX请求来处理入库操作
        // 暂时使用alert提示
        alert(`入库操作：\n耗材ID: ${consumableId}\n数量: ${quantity}\n说明: ${description}`);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('quickStockInModal'));
        modal.hide();
        
        // 刷新页面
        window.location.reload();
    });

    // 处理快速出库表单提交
    document.getElementById('quickStockOutForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const consumableId = formData.get('consumable_id');
        const quantity = formData.get('quantity');
        const description = formData.get('description');

        // 这里可以添加AJAX请求来处理出库操作
        // 暂时使用alert提示
        alert(`出库操作：\n耗材ID: ${consumableId}\n数量: ${quantity}\n说明: ${description}`);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('quickStockOutModal'));
        modal.hide();
        
        // 刷新页面
        window.location.reload();
    });

    // 处理快速入库表单提交
    document.getElementById('quickStockInForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const consumableId = formData.get('consumable_id');

        fetch(`/consumables/${consumableId}/`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': formData.get('csrfmiddlewaretoken')
            }
        }).then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert('入库操作失败，请重试');
            }
        }).catch(error => {
            alert('网络错误，请重试');
        });
    });

    // 处理快速出库表单提交
    document.getElementById('quickStockOutForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const consumableId = formData.get('consumable_id');

        fetch(`/consumables/${consumableId}/`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': formData.get('csrfmiddlewaretoken')
            }
        }).then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert('出库操作失败，请重试');
            }
        }).catch(error => {
            alert('网络错误，请重试');
        });
    });

    // ====== 通用：表单弹窗（新增/编辑） ======
    // Modal container
    (function ensureFormModal() {
        if (document.getElementById('consumableFormModal')) return;
        const wrap = document.createElement('div');
        wrap.innerHTML = `
        <div class="modal fade" id="consumableFormModal" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="consumableFormTitle">表单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <form id="consumableForm" method="post">
                {% csrf_token %}
                <div class="modal-body" id="consumableFormBody">
                  <div class="text-center text-muted py-3">加载中...</div>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                  <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-1"></i>保存
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>`;
        document.body.appendChild(wrap.firstElementChild);
    })();

    const formModalEl = document.getElementById('consumableFormModal');
    const formModal = new bootstrap.Modal(formModalEl);
    const formTitleEl = document.getElementById('consumableFormTitle');
    const formBodyEl = document.getElementById('consumableFormBody');
    const formEl = document.getElementById('consumableForm');

    function getCsrfToken() {
        const name = 'csrftoken=';
        const cookies = document.cookie ? document.cookie.split(';') : [];
        for (let c of cookies) {
            c = c.trim();
            if (c.startsWith(name)) return decodeURIComponent(c.substring(name.length));
        }
        // 兜底从模板中的隐藏输入取
        const input = document.querySelector('input[name=csrfmiddlewaretoken]');
        return input ? input.value : '';
    }

    async function openFormModal(url, title) {
        formTitleEl.textContent = title || '表单';
        formBodyEl.innerHTML = '<div class="text-center text-muted py-3">加载中...</div>';
        formEl.setAttribute('action', url);
        try {
            const resp = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await resp.json();
            if (data.success) {
                formBodyEl.innerHTML = data.html || '<div class="text-danger">未返回表单内容</div>';
            } else {
                formBodyEl.innerHTML = '<div class="text-danger">加载失败</div>';
            }
        } catch (err) {
            formBodyEl.innerHTML = '<div class="text-danger">加载失败</div>';
        }
        formModal.show();
    }

    // 打开创建
    document.getElementById('btnOpenCreateModal')?.addEventListener('click', function (e) {
        e.preventDefault();
        const url = this.getAttribute('data-modal-url');
        const title = this.getAttribute('data-modal-title');
        openFormModal(url, title);
    });

    // 打开编辑（委托）
    document.addEventListener('click', function (e) {
        const trigger = e.target.closest('[data-open-modal]');
        if (!trigger) return;
        e.preventDefault();
        const url = trigger.getAttribute('data-modal-url');
        const title = trigger.getAttribute('data-modal-title');
        openFormModal(url, title);
    });

    // 提交表单
    formEl.addEventListener('submit', async function (e) {
        e.preventDefault();
        const url = this.getAttribute('action');
        const formData = new FormData(this);
        try {
            const resp = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': getCsrfToken(),
                },
                body: formData,
            });
            const data = await resp.json();
            if (resp.ok && data.success) {
                formModal.hide();
                // 刷新当前页面以显示更新后的列表
                window.location.reload();
            } else {
                // 返回带有错误的局部表单
                formBodyEl.innerHTML = data.html || '<div class="alert alert-danger">提交失败</div>';
            }
        } catch (err) {
            formBodyEl.innerHTML = '<div class="alert alert-danger">提交异常</div>';
        }
    });

    // ===== 确认操作模态框：删除（POST） =====
    function showToast(message, type = 'info') {
        try {
            const toastEl = document.getElementById('toast');
            const toastBody = document.getElementById('toastBody');
            if (toastEl && toastBody) {
                toastEl.className = `toast align-items-center text-white bg-${type} border-0`;
                toastBody.textContent = message;
                const toast = new bootstrap.Toast(toastEl);
                toast.show();
            }
        } catch (e) { /* no-op */ }
    }

    const confirmModalEl = document.getElementById('confirmActionModal');
    const confirmTitleEl = document.getElementById('confirmActionTitle');
    const confirmMsgEl = document.getElementById('confirmActionMessage');
    const confirmBtn = document.getElementById('confirmActionBtn');
    let confirmModal = null;
    if (confirmModalEl) {
        confirmModal = new bootstrap.Modal(confirmModalEl);
    }
    async function postWithCsrf(url) {
        const token = getCsrfToken();
        const resp = await fetch(url, {
            method: 'POST',
            headers: { 'X-CSRFToken': token },
            credentials: 'same-origin'
        });
        if (!resp.ok) {
            const text = await resp.text();
            throw new Error('请求失败：' + resp.status + '\n' + text);
        }
        return resp;
    }
    document.body.addEventListener('click', function(e){
        const a = e.target.closest('a[data-modal="confirm"]');
        if (!a) return;
        e.preventDefault();
        const title = a.getAttribute('data-title') || '确认操作';
        const message = a.getAttribute('data-message') || '确定执行该操作吗？';
        const postUrl = a.getAttribute('data-post-url');
        if (confirmTitleEl) confirmTitleEl.textContent = title;
        if (confirmMsgEl) confirmMsgEl.textContent = message;
        if (confirmBtn) confirmBtn.setAttribute('data-post-url', postUrl || '');
        if (confirmModal) confirmModal.show();
    });
    if (confirmBtn) {
        confirmBtn.addEventListener('click', async function(){
            const url = confirmBtn.getAttribute('data-post-url');
            if (!url) return;
            confirmBtn.disabled = true;
            try {
                await postWithCsrf(url);
                if (confirmModal) confirmModal.hide();
                showToast('操作成功', 'success');
                setTimeout(() => window.location.reload(), 700);
            } catch (err) {
                const msg = (err && err.message) ? err.message : '请求失败，请稍后再试';
                showToast(msg, 'error');
            } finally {
                confirmBtn.disabled = false;
            }
        });
    }
</script>
{% endblock %}